<template>
  <el-form
    ref="formRef"
    :model="form"
    label-width="100px"
    style="text-align: center; padding-bottom: 10px"
  >
    <el-upload
      :headers="headers"
      class="avatar-uploader"
      :action="pre_url + '/sys/user/uploadImage'"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :on-error="handleAvatarError"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <div class="personal-button">
      <el-button v-hasPerm="['system:user:updateBaseInfo']" @click="handleConfirm"
        >确认更换</el-button
      >
    </div>
  </el-form>
</template>
<script lang="ts">
export default {
  name: "userAvatar",
};
</script>
<script setup lang="ts">
import { ref, defineProps } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { logoutSystem } from "@/utils";
import type { FormInstance, FormRules } from "element-plus";
import { usePermissStore } from "@/store/permiss";
import { useRouter } from "vue-router";
import { updateAvatar } from "@/api/user";

const router = useRouter();
const permiss = usePermissStore();
const imageUrl = ref("");
const user: any = permiss.getCurrentUser();
const props = defineProps({
  user: {
    type: Object,
    default: () => {},
    required: true,
  },
});

imageUrl.value = `${import.meta.env.VITE_APP_WEB_API}/image/userAvatar/${
  user.avatar
}`;
const pre_url = ref(import.meta.env.VITE_APP_WEB_API);

const headers = ref({
  token: permiss.getToken(),
});
interface RuleForm {
  id?: number;
  avatar?: string;
  [propName: string]: any;
}
const form = ref<RuleForm>({
  id: -1,
  avatar: "",
});
form.value = props.user;
const formRef = ref<FormInstance>();

const handleAvatarSuccess = (res) => {
  console.log(res);
  imageUrl.value = import.meta.env.VITE_APP_WEB_API + "/" + res.data.src;
  form.value.avatar = res.data.fileName;
  ElMessage.success(res.msg);
};
const handleAvatarError = (error) => {
  const data = JSON.parse(error.message);
  if (data.code == 401) {
    logoutSystem(permiss, router);
  } else {
    ElMessage.success(data.msg);
  }
};
const beforeAvatarUpload = (file) => {
  console.log(file.type);
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG && !isPNG) {
    ElMessage.error("图片必须是jpg格式或者png格式");
    return false;
  } else if (!isLt2M) {
    ElMessage.error("图片大小不能超过2M!");
    return false;
  }
  return true;
};
const handleConfirm = async () => {
  let result = await updateAvatar(form.value);
  let data = result.data;
  if (data.code == 200) {
    ElMessage.success(data.msg);
    let _userObj = sessionStorage.getItem("currentUser");
    if (_userObj) {
      let _user = JSON.parse(_userObj);
      _user["avatar"] = form.value.avatar;
      permiss.setCurrentUser(_user);
      permiss.setUserSrc(form.value.avatar||'')

    }
  } else {
    ElMessage.error(data.data);
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 50%;
}
</style>

<style>
.avatar-uploader .el-upload {
  /* border: 1px dashed #d9d9d9; */
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
  display: block;
}
.personal-button {
  margin-top: 5px;
}
</style>
